<template>
  <base-page v-bind="baseInfo">
    <template #control>
      <div class="types">
        <div v-for="(item, index) in types" :key="index" class="type" :class="{'is-active': currentType === item.code, [item.class]: true}" @click="setCurrent(item)">{{ item.title }}</div>
      </div>
    </template>
    <template #searchBar>
      <!-- <template v-if="currentType==='cost'"> -->
      <filter-form
        v-if="filterShow"
        key="1"
        ref="filterForm"
        :elements="elements"
        noimmediate
        hand
        @reset="reset"
        @submit="submit"
      />
      <!-- </template> -->
      <!-- <template v-else>
        <filter-form
          key="2"
          ref="filterForm"
          :elements="otherElements"
          :show-reset="true"
          @submit="submit"
        />
      </template> -->
    </template>
    <template #mainAside>
      <CostList :loading="tableLoading" :list="list" />
    </template>
    <template #content>
      <div class="controller">
        <div class="left">
          <Button icon="add" @click="add">新增</Button>
          <Button :loading="releaseLoading" icon="plane" @click="release">发布</Button>
        </div>
        <div class="right">
          <Button icon="order" @click="getRevision">修订记录</Button>
          <Button :loading="downloading" icon="export" @click="download">导出</Button>
        </div>
      </div>
      <div class="table-box">
        <!-- <template v-if="currentType==='cost'"> -->
        <TableNew
          v-if="tableShow"
          :loading="tableLoading"
          :data="tableData"
          :columns="getTableEl"
          :pagination="pagination"
          :table-row-class-name="showYellow"
          @paginationChange="paginationChange"
        >
          <template v-if="currentType === 'property'" #oNum="scope">
            <div>{{ scope.row.num || scope.row.id }}</div>
          </template>
          <template #yard="scope">
            <div v-if="scope.row.yard === 1">三香</div>
            <div v-else-if="scope.row.yard === 2">浒关</div>
          </template>
          <template #action="scope">
            <el-tooltip class="item" effect="dark" content="编辑" placement="top" :open-delay="600">
              <i class="el-icon-edit-outline action" @click="edit(scope.row)" />
            </el-tooltip>
            <el-tooltip class="item" effect="dark" content="删除" placement="top" :open-delay="600">
              <i class="el-icon-delete action red" @click="remove(scope.row)" />
            </el-tooltip>
          </template>
        </TableNew>
        <!-- </template>
        <template v-else>
          123
        </template> -->
        <Drawer
          ref="drawer"
          width="400px"
          :visible="drawVisible"
          :title="isEdit?'编辑':'新增'"
          :footer-btns="footerBtns"
          @confirm="confirm"
          @cancel="cancel"
        >
          <div class="drw-body">
            <el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-width="110px" size="mini">
              <el-form-item v-if="isEdit" label="用友编号" prop="num">
                <el-input v-model="ruleForm.num" disabled />
              </el-form-item>
              <el-form-item label="预算科目名称" prop="subjectId">
                <el-select v-model="ruleForm.subjectId" style="width:100%" @change="subjectChange">
                  <el-option v-for="item in subjects" :key="item.id" :label="item.subjectName" :value="item.subjectId" />
                </el-select>
              </el-form-item>
              <el-form-item label="预算科目编码" prop="subjectCode">
                <el-input v-model="ruleForm.subjectCode" disabled />
              </el-form-item>
              <el-form-item label="用友科目名称" prop="accountName">
                <el-select v-model="ruleForm.accountName" style="width:100%" :disabled="!ruleForm.subjectId" @change="accountChange">
                  <el-option v-for="item in accounts" :key="item.accountId" :label="item.accountName" :value="item.accountName" />
                </el-select>
              </el-form-item>
              <el-form-item label="用友科目编码" prop="accountCode">
                <el-input v-model="ruleForm.accountCode" disabled />
              </el-form-item>
              <el-form-item label="日期" prop="dtime">
                <el-date-picker v-model="ruleForm.dtime" type="date" format="yyyy-MM-dd" value-format="yyyy-MM-dd" style="width:100% !important" />
              </el-form-item>
              <el-form-item label="凭证号" prop="accountNum">
                <el-input v-model="ruleForm.accountNum" />
              </el-form-item>
              <el-form-item label="院区" prop="yard">
                <el-select v-model="ruleForm.yard" style="width:100%">
                  <el-option label="三香" :value="1" />
                  <el-option label="浒关" :value="2" />
                </el-select>
              </el-form-item>
              <el-form-item label="部门名称" prop="deptCode">
                <el-select v-model="ruleForm.deptCode" style="width:100%" filterable>
                  <el-option v-for="item in depts" :key="item.deptCode" :label="item.deptName" :value="item.deptCode" />
                </el-select>
              </el-form-item>
              <el-form-item label="部门编码" prop="deptCode">
                <el-input v-model="ruleForm.deptCode" disabled />
              </el-form-item>
              <el-form-item label="摘要" prop="description">
                <el-input v-model="ruleForm.description" type="textarea" />
              </el-form-item>
              <el-form-item label="金额" prop="amount">
                <el-input-number v-model="ruleForm.amount" style="width:100%;text-align: left;" :controls="false" />
              </el-form-item>
            </el-form>
          </div>
        </Drawer>
        <Drawer
          ref="drawer2"
          width="400px"
          :visible="propertyVisible"
          :title="isEdit?'编辑':'新增'"
          :footer-btns="footerBtns"
          @confirm="confirm"
          @cancel="cancel"
        >
          <div class="drw-body">
            <el-form ref="propertyForm" :model="propertyForm" :rules="propertyRules" label-width="110px" size="mini">
              <el-form-item v-if="isEdit" label="用友编号" prop="num">
                <el-input v-model="propertyForm.num" disabled />
              </el-form-item>
              <el-form-item label="预算科目名称" prop="subjectName">
                <el-select v-model="propertyForm.subjectName" style="width:100%" @change="otherSubjectChange">
                  <el-option v-for="item in otherSubjects" :key="item.subjectCode" :label="item.subjectName" :value="item.subjectName" />
                </el-select>
              </el-form-item>
              <el-form-item label="预算科目编码" prop="subjectCode">
                <el-input v-model="propertyForm.subjectCode" disabled />
              </el-form-item>
              <el-form-item label="固定资产名称" prop="assetName">
                <el-input v-model="propertyForm.assetName" />
              </el-form-item>
              <el-form-item label="固定资产编码" prop="assetNum">
                <el-input v-model="propertyForm.assetNum" />
              </el-form-item>
              <el-form-item label="院区" prop="yard">
                <el-select v-model="propertyForm.yard" style="width:100%">
                  <el-option label="三香" :value="1" />
                  <el-option label="浒关" :value="2" />
                </el-select>
              </el-form-item>
              <el-form-item label="部门名称" prop="deptCode">
                <el-select v-model="propertyForm.deptCode" style="width:100%" filterable>
                  <el-option v-for="item in depts" :key="item.deptCode" :label="item.deptName" :value="item.deptCode" />
                </el-select>
              </el-form-item>
              <el-form-item label="部门编码" prop="deptCode">
                <el-input v-model="propertyForm.deptCode" disabled />
              </el-form-item>
              <el-form-item label="原值" prop="originalValue">
                <el-input-number v-model="propertyForm.originalValue" style="width:100%;text-align: left;" :controls="false" />
              </el-form-item>
              <el-form-item label="开始使用日期" prop="useStartDate">
                <el-date-picker v-model="propertyForm.useStartDate" type="date" format="yyyy-MM-dd" value-format="yyyy-MM-dd" style="width:100% !important" @change="useStartDateChange" />
              </el-form-item>
              <el-form-item label="存放地点" prop="site">
                <el-input v-model="propertyForm.site" />
              </el-form-item>
              <el-form-item label="使用人" prop="operator">
                <el-input v-model="propertyForm.operator" />
              </el-form-item>
              <el-form-item label="数据月份" prop="period">
                <el-date-picker v-model="propertyForm.period" type="month" format="yyyyMM" value-format="yyyyMM" style="width:100% !important" disabled />
              </el-form-item>
            </el-form>
          </div>
        </Drawer>
      </div>
    </template>
  </base-page>
</template>

<script>
import baseFilterTable from '@/mixins/baseFilterTable'

import {
  getBusinessBudgetList,
  insertBusinessBudget,
  updateBusinessAccountByNum,
  deleteByNum,
  releaseData,
  exportExcelYsBusinessBudget,
  getAssetInfoList,
  insertBusinessAsset,
  updateBusinessAssetByNum,
  AssetReleaseData,
  deleteByNumOther,
  exportExcelYsManageAsset
} from '@/api/collectionManage/businessExecute'

import {
  listYsSubject4,
  listYsBusinessSubject,
  listYsDepartment,
  getYyDept
} from '@/api/public.js'

export default {
  name: 'BusinessExecute', // 业务-预算执行管理
  components: {},
  mixins: [baseFilterTable],
  beforeRouteEnter(to, from, next) {
    if (from.params.mode) {
      next(vm => {
        switch (from.params.mode) {
          case '1':
            vm.currentType = 'cost'
            break
          case '5':
            vm.currentType = 'property'
            break
        }
      })
    }
    next()
  },
  props: {},
  data() {
    return {
      types: [
        {
          title: '费用类',
          class: 'cost',
          code: 'cost'
        },
        {
          title: '资产类',
          class: 'property',
          code: 'property'
        }
      ],
      currentType: 'cost',
      isEdit: false,
      baseInfo: {
        mainAsideWidth: 260,
        mainAsideShow: true,
        searchBarShow: true,
        controlShow: true
      },
      list: [],
      tableData: [],
      tableEl: [
        {
          title: '编号',
          dataIndex: 'num'
        },
        {
          title: '预算科目名称',
          dataIndex: 'subjectName',
          width: 120
        },
        {
          title: '预算科目编码',
          dataIndex: 'subjectCode',
          width: 120
        },
        {
          title: '用友科目编码',
          dataIndex: 'accountCode',
          width: 120
        },
        {
          title: '用友科目名称',
          dataIndex: 'accountName',
          width: 120
        },
        {
          title: '日期',
          dataIndex: 'dateTime',
          width: 100
        },
        {
          title: '凭证号',
          dataIndex: 'accountNum'
        },
        {
          title: '部门编码',
          dataIndex: 'deptCode'
        },
        {
          title: '部门名称',
          dataIndex: 'deptName',
          width: 100
        },
        {
          title: '摘要',
          dataIndex: 'description',
          width: 200
        },
        {
          title: '金额（元）',
          dataIndex: 'amount',
          width: 90,
          format: true,
          align: 'right'
        },
        {
          title: '院区',
          dataIndex: 'yard',
          type: 'otherTag'
        },
        {
          title: '操作',
          dataIndex: 'action',
          type: 'otherTag',
          align: 'center'
        }
      ],
      otherEl: [
        {
          title: '用友编号',
          dataIndex: 'oNum',
          type: 'otherTag'
        },
        {
          title: '预算科目名称',
          dataIndex: 'subjectName',
          width: 120
        },
        {
          title: '预算科目编码',
          dataIndex: 'subjectCode',
          width: 120
        },
        {
          title: '固定资产编码',
          dataIndex: 'assetNum',
          width: 120
        },
        {
          title: '固定资产名称',
          dataIndex: 'assetName',
          width: 120
        },
        {
          title: '部门编码',
          dataIndex: 'deptCode'
        },
        {
          title: '部门名称',
          dataIndex: 'deptName',
          width: 100
        },
        {
          title: '原值',
          dataIndex: 'originalValue',
          format: true,
          align: 'right'
        },
        {
          title: '开始使用日期',
          dataIndex: 'useStartDate',
          width: 120
        },
        {
          title: '存放地点',
          dataIndex: 'site'
        },
        {
          title: '使用人',
          dataIndex: 'operator'
        },
        {
          title: '院区',
          dataIndex: 'yard',
          type: 'otherTag'
        },
        {
          title: '操作',
          dataIndex: 'action',
          type: 'otherTag',
          align: 'center',
          width: 90
        }
      ],
      elements: [
        {
          label: '时间',
          type: 'date-picker',
          mode: 'monthrange',
          key: 'time',
          value: [],
          format: 'yyyyMM',
          choiceDate: '',
          pickerOptions: this.$pickerOptions(),
          change: val => this.$pickerOptions(val => {
            if (!val) {
              const target = this.elements.find(i => i.type === 'date-picker' && i.mode === 'monthrange')
              target.choiceDate = ''
              const target2 = this.otherElements.find(i => i.type === 'date-picker' && i.mode === 'monthrange')
              target2.choiceDate = ''
            }
          })
        },
        {
          label: '院区',
          type: 'select',
          options: [
            {
              label: '三香',
              value: 1
            },
            {
              label: '浒关',
              value: 2
            }
          ],
          key: 'yard',
          value: ''
        },
        {
          label: '部门名称',
          type: 'select',
          options: [],
          key: 'deptName',
          value: ''
        },
        {
          label: '用友编号',
          type: 'input',
          key: 'number',
          value: ''
        },
        {
          label: '综合搜索',
          type: 'input',
          key: 'column',
          value: '',
          placeholder: '请输入预算科目名称/预算科目编码/科目名称/科目编码',
          width: 320
        }
      ],
      otherElements: [
        {
          label: '时间',
          type: 'date-picker',
          mode: 'monthrange',
          key: 'time',
          value: [],
          format: 'yyyyMM',
          choiceDate: '',
          pickerOptions: this.$pickerOptions(),
          change: val => this.$pickerOptions(val => {
            if (!val) {
              const target = this.elements.find(i => i.type === 'date-picker' && i.mode === 'monthrange')
              target.choiceDate = ''
              const target2 = this.otherElements.find(i => i.type === 'date-picker' && i.mode === 'monthrange')
              target2.choiceDate = ''
            }
          })
        },
        {
          label: '院区',
          type: 'select',
          options: [
            {
              label: '三香',
              value: 1
            },
            {
              label: '浒关',
              value: 2
            }
          ],
          key: 'yard',
          value: ''
        },
        {
          label: '部门名称',
          type: 'select',
          options: [],
          key: 'deptName',
          value: ''
        },
        {
          label: '用友编号',
          type: 'input',
          key: 'number',
          value: ''
        },
        {
          label: '综合搜索',
          type: 'input',
          key: 'column',
          value: '',
          placeholder: '请输入预算科目名称/预算科目编码/科目名称/科目编码',
          width: 320
        }
      ],
      drawVisible: false,
      propertyVisible: false,
      footerBtns: [
        {
          text: '保存',
          trigger: 'confirm'
        },
        {
          text: '取消',
          trigger: 'cancel',
          type: 'info'
        }
      ],
      ruleForm: {
        num: '',
        accountName: '',
        accountCode: '',
        subjectId: '',
        subjectCode: '',
        dtime: '',
        accountNum: '',
        yard: '',
        deptCode: '',
        description: '',
        amount: ''
      },
      rules: {
        accountName: [
          { required: true, message: '请选择科目名称', trigger: 'change' }
        ],
        subjectId: [
          { required: true, message: '请选择预算科目名称', trigger: 'change' }
        ],
        dtime: [
          { required: true, message: '请选择日期', trigger: 'change' }
        ],
        deptCode: [
          { required: true, message: '请选择部门名称', trigger: 'change' }
        ],
        amount: [
          { required: true, message: '请输入金额', trigger: 'blur' }
        ],
        yard: [
          { required: true, message: '请选择院区', trigger: 'change' }
        ]
      },
      propertyForm: {
        subjectName: '',
        subjectCode: '',
        assetName: '',
        assetNum: '',
        yard: '',
        deptCode: '',
        originalValue: '',
        useStartDate: '',
        site: '',
        operator: '',
        period: ''
      },
      propertyRules: {
        subjectName: [
          { required: true, message: '请选择预算科目名称', trigger: 'change' }
        ],
        assetName: [
          { required: true, message: '请输入固定资产名称', trigger: 'blur' }
        ],
        assetNum: [
          { required: true, message: '请输入固定资产编码', trigger: 'blur' }
        ],
        deptCode: [
          { required: true, message: '请选择部门名称', trigger: 'change' }
        ],
        originalValue: [
          { required: true, message: '请输入原值', trigger: 'blur' }
        ],
        yard: [
          { required: true, message: '请选择院区', trigger: 'change' }
        ],
        useStartDate: [
          { required: true, message: '请选择开始使用日期', trigger: 'change' }
        ],
        period: [
          { required: true, message: '请选择数据月份', trigger: 'change' }
        ]
      },
      otherSubjects: [
        {
          subjectName: '医疗设备',
          subjectCode: '10020101'
        },
        {
          subjectName: '一般设备',
          subjectCode: '10020102'
        },
        {
          subjectName: '信息设备',
          subjectCode: '10020103'
        },
        {
          subjectName: '专用软件',
          subjectCode: '10020201'
        }
      ],
      accounts: [],
      subjects: [],
      depts: [],
      currentId: '',
      releaseLoading: false,
      downloading: false,
      filterShow: true,
      tableShow: true
    }
  },
  computed: {
    getTableEl() {
      if (this.currentType === 'cost') {
        return this.tableEl
      } else {
        return this.otherEl
      }
    }
  },
  created() {
    this.elements[3].value = this.$route.query.num
    this._listYsSubject4()
    this._listYsDepartment()
    this._getYyDept()
    this.initMonth()
  },
  mounted() {
    if (this.$route.query.sourceNum) {
      this.$nextTick(() => {
        setTimeout(() => {
          this.setCurrent(this.types[Number(this.$route.query.sourceNum) - 2])
        }, 1000)
      })
    } else {
      this.currentType = 'cost'
      this.submit()
    }
  },
  methods: {
    async _listYsSubject4() {
      try {
        const { data } = await listYsSubject4()
        if (data.code === 200) {
          this.subjects = data.data.map(({ subjectName, subjectCode, id }) => ({ subjectId: id, subjectCode, subjectName }))
        } else {
          this.$message.error(data.message || '获取失败')
        }
      } catch (error) {
        console.log(error)
      }
    },
    subjectChange(val) {
      this.ruleForm.subjectCode = this.subjects.find(i => i.subjectId === val)?.subjectCode
      this._listYsBusinessSubject(val)
    },
    accountChange(val) {
      this.ruleForm.accountCode = this.accounts.find(i => i.accountName === val)?.accountCode
    },
    deptChange(val) {
      this.ruleForm.deptCode = this.depts.find(i => i.deptId === val)?.deptCode
    },
    async _listYsBusinessSubject(val) {
      try {
        const { data } = await listYsBusinessSubject({
          subjectId: val
        })
        if (data.code === 200) {
          this.accounts = data.data.map(i => ({ accountId: i.id, accountName: i.yySubjectName, accountCode: i.yySubjectCode }))
        } else {
          this.$message.error(data.message || '获取失败')
        }
      } catch (error) {
        console.log(error)
      }
    },
    async _listYsDepartment() {
      try {
        const { data } = await listYsDepartment({ status: 1 })
        if (data.code === 200) {
          this.elements.find(i => i.key === 'deptName').options.push(...data.data.map(j => ({ label: j.departmentName, value: j.departmentName })))
          // this.depts.push(...data.data.map(i => ({ deptId: i.id, deptName: i.departmentName, deptCode: i.departmentCode })))
        } else {
          this.$message.error(data.message || '部门获取失败')
        }
      } catch (error) {
        console.log(error)
      }
    },
    async _getYyDept() {
      try {
        const { data } = await getYyDept()
        if (data.code === 200) {
          this.depts.push(...data.data.map(i => ({ deptId: i.deptId, deptName: i.deptName, deptCode: i.deptCode })))
        } else {
          this.$message.error(data.message || '部门获取失败')
        }
      } catch (error) {
        console.log(error)
      }
    },
    initMonth() {
      const { startTime, endTime } = this.$getQuarter()
      this.elements.find(i => i.type === 'date-picker' && i.mode === 'monthrange').value.push(startTime, endTime)
    },
    async getData(val) {
      const params = {
        startTime: val?.time?.length ? parseInt(val.time[0]) : '',
        endTime: val?.time?.length ? parseInt(val.time[1]) : '',
        yard: val?.yard || '',
        deptName: val?.deptName || '',
        number: val?.number || '',
        column: val?.column || '',
        type: '1',
        pageSize: this.pagination.pageSize,
        pageNum: this.pagination.current
      }
      if (this.currentType === 'cost') {
        try {
          this.tableLoading = true
          const { data } = await getBusinessBudgetList(params)
          if (data.code === 200) {
            const arr = data.data.expenseVOList
            arr.sort((next, cur) => {
              return next.sort - cur.sort
            })
            this.list = arr.map(i => ({ label: i.subjectName, value: i.amount }))
            this.tableData = data?.data?.detailList?.list || []
            this.pagination.total = data?.data?.detailList?.total || 0
          } else {
            console.log(data)
          }
          this.tableLoading = false
        } catch (error) {
          this.tableLoading = false
          console.log(error)
        }
      } else {
        try {
          const { data } = await getAssetInfoList(params)
          if (data.code === 200) {
            const arr = data.data.expenseVOList
            arr.sort((next, cur) => {
              return next.sort - cur.sort
            })
            this.list = arr.map(i => ({ label: i.subjectName, value: i.amount }))
            this.tableData = data?.data?.detailList?.list || []
            this.pagination.total = data?.data?.detailList?.total || 0
          } else {
            console.log(data)
          }
        } catch (error) {
          console.log(error)
        } finally {
          this.tableLoading = false
        }
      }
    },
    getRevision() {
      const types = {
        cost: 1,
        property: 5
      }
      this.$router.push({
        path: '/revision-record',
        query: {
          mode: types[this.currentType]
        }
      })
      // this.$bus.$emit('handleFrame', url.href, true)
    },
    add() {
      this.isEdit = false
      if (this.currentType === 'cost') {
        this.drawVisible = true
      } else {
        this.propertyVisible = true
      }
    },
    edit(item) {
      console.log(item)
      this.isEdit = true
      if (this.currentType === 'cost') {
        this.currentId = item.id
        this.drawVisible = true
        this.$nextTick(() => {
          this.ruleForm.num = item.num
          this.ruleForm.accountName = item.accountName
          this.ruleForm.accountCode = item.accountCode
          this.ruleForm.subjectId = item.subjectId
          this.ruleForm.subjectCode = item.subjectCode
          this.ruleForm.dtime = item.dateTime
          this.ruleForm.accountNum = item.accountNum
          this.ruleForm.yard = item.yard
          this.ruleForm.deptCode = item.deptCode
          this.ruleForm.description = item.description
          this.ruleForm.amount = item.amount
        })
      } else {
        this.propertyVisible = true
        this.$nextTick(() => {
          this.currentId = item.id
          this.propertyForm.subjectName = item.subjectName
          this.propertyForm.subjectCode = item.subjectCode
          this.propertyForm.assetName = item.assetName
          this.propertyForm.assetNum = item.assetNum
          this.propertyForm.yard = item.yard
          this.propertyForm.deptCode = item.deptCode
          this.propertyForm.originalValue = item.originalValue
          this.propertyForm.useStartDate = item.useStartDate
          this.propertyForm.site = item.site
          this.propertyForm.operator = item.operator
          this.propertyForm.num = item.num || item.id
          this.propertyForm.period = item.period + ''
        })
      }
    },
    confirm() {
      if (this.currentType === 'cost') {
        this.$refs.ruleForm.validate(async v => {
          if (v) {
            this.$refs.drawer.loadOn('confirm')
            if (!this.isEdit) {
              const params = {
                accountCode: this.ruleForm.accountCode,
                accountName: this.ruleForm.accountName,
                accountNum: this.ruleForm.accountNum,
                amount: this.ruleForm.amount,
                deptCode: this.ruleForm.deptCode,
                description: this.ruleForm.description,
                num: this.ruleForm.num,
                dtime: this.ruleForm.dtime,
                subjectId: this.ruleForm.subjectId,
                type: '1',
                yard: this.ruleForm.yard
              }
              try {
                const { data } = await insertBusinessBudget(params)
                if (data.code === 200) {
                  this.$message.success(data.message || '操作成功')
                  this.cancel()
                  this.$refs.filterForm.submitFormFilter()
                } else {
                  this.$message.error(data.message || '操作失败')
                }
              } catch (error) {
                console.log(error)
              } finally {
                this.$refs.drawer.loadOff('confirm')
              }
            } else {
              const params = {
                id: this.currentId,
                accountCode: this.ruleForm.accountCode,
                accountName: this.ruleForm.accountName,
                accountNum: this.ruleForm.accountNum,
                amount: this.ruleForm.amount,
                deptCode: this.ruleForm.deptCode,
                description: this.ruleForm.description,
                num: this.ruleForm.num,
                dtime: this.ruleForm.dtime,
                subjectId: this.ruleForm.subjectId,
                yard: this.ruleForm.yard
              }
              try {
                const { data } = await updateBusinessAccountByNum(params)
                if (data.code === 200) {
                  this.$message.success(data.message || '操作成功')
                  this.cancel()
                  this.$refs.filterForm.submitFormFilter()
                } else {
                  this.$message.error(data.message || '操作失败')
                }
              } catch (error) {
                console.log(error)
              } finally {
                this.$refs.drawer.loadOff('confirm')
              }
            }
          }
        })
      } else {
        this.$refs.propertyForm.validate(async v => {
          if (v) {
            this.$refs.drawer2.loadOn('confirm')
            if (!this.isEdit) {
              const params = {
                subjectName: this.propertyForm.subjectName,
                subjectCode: this.propertyForm.subjectCode,
                assetName: this.propertyForm.assetName,
                assetNum: this.propertyForm.assetNum,
                yard: this.propertyForm.yard,
                deptCode: this.propertyForm.deptCode,
                deptName: this.depts.find(i => i.deptCode === this.propertyForm.deptCode).deptName,
                originalValue: this.propertyForm.originalValue,
                useStartDate: this.propertyForm.useStartDate,
                site: this.propertyForm.site,
                operator: this.propertyForm.operator,
                period: this.propertyForm.period
              }
              try {
                const { data } = await insertBusinessAsset(params)
                if (data.code === 200) {
                  this.$message.success(data.message || '操作成功')
                  this.cancel()
                  this.$refs.filterForm.submitFormFilter()
                } else {
                  this.$message.error(data.message || '操作失败')
                }
              } catch (error) {
                console.log(error)
              } finally {
                this.$refs.drawer2.loadOff('confirm')
              }
            } else {
              const params = {
                subjectName: this.propertyForm.subjectName,
                subjectCode: this.propertyForm.subjectCode,
                assetName: this.propertyForm.assetName,
                assetNum: this.propertyForm.assetNum,
                deptCode: this.propertyForm.deptCode,
                deptName: this.depts.find(i => i.deptCode === this.propertyForm.deptCode).deptName,
                id: this.currentId,
                num: this.propertyForm.num,
                operator: this.propertyForm.operator,
                originalValue: this.propertyForm.originalValue,
                period: this.propertyForm.period,
                site: this.propertyForm.site,
                useStartDate: this.propertyForm.useStartDate,
                yard: this.propertyForm.yard
              }
              try {
                const { data } = await updateBusinessAssetByNum(params)
                if (data.code === 200) {
                  this.$message.success(data.message || '操作成功')
                  this.cancel()
                  this.$refs.filterForm.submitFormFilter()
                } else {
                  this.$message.error(data.message || '操作失败')
                }
              } catch (error) {
                console.log(error)
              } finally {
                this.$refs.drawer2.loadOff('confirm')
              }
            }
          }
        })
      }
    },
    remove(item) {
      if (this.currentType === 'cost') {
        this.$confirm({
          content: '此操作将删除该条数据，是否继续？',
          title: '确认信息',
          okFn: async(res) => {
            const params = {
              id: item.id
              // yard: item.yard
            }
            try {
              const { data } = await deleteByNum(params)
              if (data.code === 200) {
                this.$message.success(data.message || '操作成功')
                this.$refs.filterForm.submitFormFilter()
              } else {
                this.$message.error(data.message || '操作失败')
              }
            } catch (error) {
              console.log(error)
            }
          },
          cancelFn: (res) => {
            console.log('取消')
          }
        })
      } else {
        this.$confirm({
          content: '此操作将删除该条数据，是否继续？',
          title: '确认信息',
          okFn: async(res) => {
            const params = {
              id: item.id
            }
            console.log(params)
            try {
              const { data } = await deleteByNumOther(params)
              if (data.code === 200) {
                this.$message.success(data.message || '操作成功')
                this.$refs.filterForm.submitFormFilter()
              } else {
                this.$message.error(data.message || '操作失败')
              }
            } catch (error) {
              console.log(error)
            }
          },
          cancelFn: (res) => {
            console.log('取消')
          }
        })
      }
    },
    cancel() {
      this.currentId = ''
      if (this.currentType === 'cost') {
        this.$refs.ruleForm.resetFields()
        this.drawVisible = false
      } else {
        this.$refs.propertyForm.resetFields()
        this.propertyVisible = false
      }
    },
    showYellow({ row }) {
      if (row.insertFlag !== 0) return 'yellow'
    },
    async release() {
      const val = this.$refs.filterForm.getParms()
      if (this.currentType === 'cost') {
        this.$confirm({
          content: '发布后，将费用类的预算执行数据下发至各科室，是否继续发布？',
          title: '确认提示',
          okFn: async() => {
            const params = {
              startTime: val?.time?.length ? parseInt(val.time[0]) : '',
              endTime: val?.time?.length ? parseInt(val.time[1]) : '',
              yard: val?.yard || '',
              deptName: val?.deptName || '',
              number: val?.number || '',
              column: val?.column || '',
              type: '1',
              pageSize: this.pagination.pageSize,
              pageNum: this.pagination.current
            }
            this.releaseLoading = true
            try {
              const { data } = await releaseData(params)
              if (data.code === 200) {
                this.$message.success(data.message || '操作成功')
              } else {
                this.$message.error(data.message || '操作失败')
              }
            } catch (error) {
              console.log(error)
            } finally {
              this.releaseLoading = false
            }
          },
          cancelFn: () => {}
        })
      } else {
        this.$confirm({
          content: '发布后，将资产类的预算执行数据下发至各科室，是否继续发布？',
          title: '确认提示',
          okFn: async() => {
            const params = {
              startTime: val?.time?.length ? parseInt(val.time[0]) : '',
              endTime: val?.time?.length ? parseInt(val.time[1]) : '',
              yard: val?.yard || '',
              deptName: val?.deptName || '',
              number: val?.number || '',
              column: val?.column || '',
              type: '1',
              pageSize: this.pagination.pageSize,
              pageNum: this.pagination.current
            }
            this.releaseLoading = true
            try {
              const { data } = await AssetReleaseData(params)
              if (data.code === 200) {
                this.$message.success(data.message || '操作成功')
              } else {
                this.$message.error(data.message || '操作失败')
              }
            } catch (error) {
              console.log(error)
            } finally {
              this.releaseLoading = false
            }
          },
          cancelFn: () => {}
        })
      }
    },
    async download() {
      const type = {
        cost: exportExcelYsBusinessBudget,
        property: exportExcelYsManageAsset
      }
      const val = this.$refs.filterForm.getParms()
      const params = {
        startTime: val?.time?.length ? parseInt(val.time[0]) : '',
        endTime: val?.time?.length ? parseInt(val.time[1]) : '',
        yard: val?.yard || '',
        deptName: val?.deptName || '',
        number: val?.number || '',
        column: val?.column || ''
      }
      this.downloading = true
      try {
        const res = await type[this.currentType](params)
        if (res.data.type === 'application/json') {
          this.$message.error('下载失败')
        } else {
          const blob = new Blob([res.data])
          const fileName = `${this.types.find(i => i.code === this.currentType).title}` + '.xlsx'
          const URL = window.URL || window.webkitURL || window.moxURL
          if ('download' in document.createElement('a')) {
          // 非IE下载
            const elink = document.createElement('a')
            elink.download = fileName // 命名下载名称
            elink.style.display = 'none'
            elink.href = URL.createObjectURL(blob) // 表示一个指定的file对象或Blob对象
            document.body.appendChild(elink)
            elink.click() // 点击触发下载
            URL.revokeObjectURL(elink.href) // 释放URL 对象
            document.body.removeChild(elink)
          } else {
          // IE10+下载
            navigator.msSaveBlob(blob, fileName)
          }
        }
      } catch (error) {
        console.log(error)
      } finally {
        this.downloading = false
      }
    },
    setCurrent(item) {
      this.tableData = []
      this.list = []
      this.currentType = item.code
      this.tableShow = false
      this.$nextTick(() => {
        this.filterShow = false
        this.tableShow = true
        this.$nextTick(() => {
          this.filterShow = true
          this.$nextTick(() => {
            this.$refs.filterForm.submitFormFilter()
          })
        })
      })
    },
    otherSubjectChange(val) {
      this.propertyForm.subjectCode = this.otherSubjects.find(i => i.subjectName === val)?.subjectCode
    },
    useStartDateChange(val) {
      if (val) {
        const dateArr = val.split('-')
        this.propertyForm.period = dateArr[0] + dateArr[1]
      }
    },
    reset() {
      const { startTime, endTime } = this.$getQuarter()
      this.initMonth()
      const obj = {}
      this.elements.forEach(i => {
        if (Array.isArray(i.value)) {
          if (i.key === 'time') {
            obj.time = [startTime, endTime]
          } else {
            obj[i.key] = []
          }
        } else {
          obj[i.key] = ''
        }
      })
      this.$refs.filterForm.handleForceSet(obj)
      this.$refs.filterForm.submitFormFilter()
    }
  }
}
</script>

<style lang="less" scoped>
.table-box{
  height: calc(100% - 36px);
  display: flex;
  flex-direction: column;
}
.controller{
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
}
.left,
.right{
  display: flex;
  :deep(.ck-button) {
    margin-right: 8px;
  }
  :deep(.ck-button:last-of-type) {
    margin-right: 0;
  }
}
.red{
  color: #F56C6C;
}
.drw-body{
  height: 100%;
  overflow-y: auto;
  padding: 8px;
  :deep(.el-input-number input) {
    text-align: left;
  }
}
:deep(.yellow td){
  background-color: rgb(250, 236, 216) !important;
}
.types{
  display: flex;
}
.type{
  color: #fff;
  padding: 4px;
  border-radius: 4px;
  margin-right: 8px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 112px;
  border: 2px solid transparent;
  transition: all .3s;
}
.is-active{
  border: 2px solid #2165f9;
}
.cost{
  background-color: #93d2f3;
}
.property{
  background-color: #e99d42;
}
</style>
